package com.itheima.vms.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.vms.domain.po.ItemCategory;
import com.itheima.vms.mapper.CategoryMapper;
import com.itheima.vms.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 商品分类表 服务实现类
 * </p>
 *
 * @author shenkunlin
 * @since 2025-08-02
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, ItemCategory> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<ItemCategory> list() {
        return categoryMapper.selectList(new HashMap<>());
    }

    @Override
    public List<ItemCategory> listAll() {
//        //查询所有
//        List<ItemCategory> list = categoryMapper.listAll();
//        //分出父类和子类
//        List<ItemCategory> parents = list.stream().filter(parent -> parent.getParentId() == null || parent.getParentId() == 0).toList();
//        List<ItemCategory> childrens = list.stream().filter(children -> children.getParentId() != null && children.getParentId() != 0).toList();
//        //循环每一个顶级父类，找到属于他的子类
//        parents.forEach(parent->{
//            findChindren(parent,childrens);
//        });
//        return parents;
//    }

        // 获取所有分类
        List<ItemCategory> allCategories = categoryMapper.listAll();

        // 构建树形结构
        Map<Integer, ItemCategory> categoryMap = new HashMap<>();
        for (ItemCategory category : allCategories) {
            categoryMap.put(category.getId(), category);
        }

        List<ItemCategory> rootCategories = new ArrayList<>();
        for (ItemCategory category : allCategories) {
            if (category.getParentId() == null || category.getParentId() == 0) {
                rootCategories.add(category);
            } else {
                ItemCategory parent = categoryMap.get(category.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(category);
                }
            }
        }

        return rootCategories;
    }

    //递归调用 给每个父类找到它的子类，之后找到它子类的子类
    private void findChindren(ItemCategory parent, List<ItemCategory> children) {
        //找到属于它的子类
        List<ItemCategory> childrens = children.stream().filter(c-> c.getParentId() != null && Objects.equals(c.getParentId(),parent.getId())).toList();
        //如果不为空，就是找到了它的子类，就要找它的子类的的子类
        //如果为空就要跳出这个递归
        if(ObjectUtil.isNotEmpty(childrens)){
            childrens.forEach(d->findChindren(d,children));
        }
        //给父类来设置它的子类集合
        parent.setChildren(childrens);
    }
}